package com.example.aaa;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Instances;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;

public class AAAViewsFactory implements RemoteViewsService.RemoteViewsFactory {
  private List<String> items;
  
  private Context context = null;
  //private int appWidgetId;

  public AAAViewsFactory(Context context, Intent intent) {
      this.context = context;
      this.items = new ArrayList<String>();
      final int eventCount = 4;
      int eventsInResult = 0;

      Calendar calendar = new GregorianCalendar();
      Long start = calendar.getTimeInMillis();
      calendar.add(Calendar.DAY_OF_MONTH, 31);
      Long end = calendar.getTimeInMillis();

      String[] proj = new String[] { Instances.EVENT_ID, Instances.BEGIN, Instances.END };
      Cursor cursor = Instances.query(context.getContentResolver(), proj, start, end);
      
      if (cursor.getCount() == 0) {
      	Log.e("Widget", "No events in given range");
      	return;
      }
  	
      cursor.moveToFirst();
      
      try {
      		String lastEventId = "";
	      	while (eventsInResult < eventCount && cursor.isAfterLast() == false) {
	      		String eventId = cursor.getString(0);
	      		if (eventId == lastEventId) {
	      			cursor.moveToNext();
	      			continue;
	      		}
	      		
	      		lastEventId = eventId;
	  			Long startTime = cursor.getLong(1);
	  			Long endTime = cursor.getLong(2);
	  			Event event = getEvent(context, eventId);
	  			
	  			Format formatter = getFormatter(true, event.isAllDay == false);
	  			
	  			String item = event.title + " " + formatter.format(startTime);
	  			if (event.numberOfDays == 0) {
	  				item += " - " + getFormatter(false, true).format(endTime);
	  			} else if (event.numberOfDays > 1) {
	  				item += " - " + formatter.format(endTime); 
	  			}
	  			
	  			eventsInResult++;
	  			items.add(item);
	  			
	  			cursor.moveToNext();
	      	}
		} catch (Exception e) {
			Log.e("Widget", "Exceptiont thrown while reading event information");
		}
     
      //this.appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
      //                                		AppWidgetManager.INVALID_APPWIDGET_ID);
  }
  
  private Format getFormatter(boolean showDate, boolean showTime) {
  	String format = "";
  	if (showDate) {
  		format += "dd/MM/yyyy";
  	}
  	if (showTime) {
  		format += " HH:mm";
  	}
  	
  	SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.getDefault());
  	formatter.setTimeZone(TimeZone.getTimeZone("Israel/Jerusalem"));
  	
		return formatter;
  }
  
  private Event getEvent(Context context, String eventId) throws Exception {
  	String[] projection = new String[] { CalendarContract.Events.TITLE, 
									   		 CalendarContract.Events.ALL_DAY,
									   		 CalendarContract.Events.DTSTART,
									   		 CalendarContract.Events.DTEND};
  	Cursor eventCursor = context.getContentResolver().query(
  			CalendarContract.Events.CONTENT_URI, 
  			projection, 
  			CalendarContract.Events._ID + " = ?", 
  			new String[] { eventId }, 
  			null);
  	
  	if (eventCursor.getCount() == 0) {
  		Log.e("Widget", "No event with given ID!");
  		throw new Exception("No event with given ID found");
  	}
  	
  	eventCursor.moveToFirst(); 
  	
  	return new Event(eventCursor.getString(0), 
  					 eventCursor.getInt(1) == 1,
  					 eventCursor.getLong(2),
  					 eventCursor.getLong(3));
  }
  
  @Override
  public void onCreate() {}
  
  @Override
  public void onDestroy() {}

  @Override
  public int getCount() {
    return(items.size());
  }

  @Override
  public RemoteViews getViewAt(int position) {
    RemoteViews row=new RemoteViews(context.getPackageName(), R.layout.row);
    
    row.setTextViewText(android.R.id.text1, items.get(position));

    //Intent i=new Intent();
    //Bundle extras=new Bundle();
    
    //extras.putString(WidgetProvider.EXTRA_WORD, items[position]);
    //i.putExtras(extras);
    //row.setOnClickFillInIntent(android.R.id.text1, i);

    return(row);
  }

  @Override
  public RemoteViews getLoadingView() {
    return(null);
  }
  
  @Override
  public int getViewTypeCount() {
    return(1);
  }

  @Override
  public long getItemId(int position) {
    return(position);
  }

  @Override
  public boolean hasStableIds() {
    return(true);
  }

  @Override
  public void onDataSetChanged() {}
}